package com.example.demo.utils;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import org.springframework.beans.factory.annotation.Value;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtils {
    @Value("${rsa.private_key}")
    private String secretKey;

    @Value("${jwt.expiration}")
    private Long expiration;

    //生成token
    public String generateToken(String username, String userId) {
        Map<String, Object> payload = new HashMap<>();
        payload.put("userId", userId);
        payload.put("username", username);
        payload.put("iat", new Date().getTime() / 1000);
        payload.put("exp", (new Date().getTime() + expiration) / 1000);
        return JWTUtil.createToken(payload, secretKey.getBytes());
    }

    //验证token
    public Boolean validateToken(String token) {
        return JWTUtil.verify(token, secretKey.getBytes());
    }

    //JWT解析
    public String getUserInforFromToken(String token) {
        final JWT jwt = JWTUtil.parseToken(token);
        return (String) jwt.getPayload("username");
    }
}
